import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Card,
  Button,
  Input,
  Table,
  Form,
  Modal,
  Divider,
  Popconfirm,
  Row,
  Col,
  TreeSelect,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './style.less';

const FormItem = Form.Item;
const { Search, TextArea } = Input;
const { TreeNode } = TreeSelect;

const ProductModelForm = Form.create()(props => {
  const { modalVisible, form, handleModalVisible, handleAdd, modelClassData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleAdd(fieldsValue, form);
    });
  };
  // 组件树形控件 子节点渲染
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} value={item.id}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.id} value={item.id}></TreeNode>;
    });

  return (
    <Modal
      title={formatMessage({ id: 'app.mm.productmodel.add' })}
      destroyOnClose
      visible={modalVisible}
      width={618}
      onOk={okHandle}
      maskClosable={false}
      onCancel={() => handleModalVisible()}
    >
      <div style={{ width: 530, paddingLeft: 44 }}>
        <FormItem label={formatMessage({ id: 'app.mm.productmodel.info.name' })} colon={false}>
          {form.getFieldDecorator('name', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.mm.productmodel.info.name.place' }),
              },
            ],
          })(<Input placeholder={formatMessage({ id: 'app.mm.productmodel.info.name.place' })} />)}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.mm.productmodel.info.class' })} colon={false}>
          {form.getFieldDecorator('classId', {
            message: formatMessage({ id: 'app.mm.productmodel.info.class.place' }),
          })(
            <TreeSelect
              showSearch
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder={formatMessage({ id: 'app.mm.productmodel.info.class.place' })}
              allowClear
              treeDefaultExpandAll
            >
              {renderTreeNodes(modelClassData)}
            </TreeSelect>,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.mm.productmodel.info.desc' })} colon={false}>
          {form.getFieldDecorator('desc', {
            rules: [],
          })(<TextArea rows={4} />)}
        </FormItem>
      </div>
    </Modal>
  );
});
@connect(({ productmodel, loading }) => ({
  productmodel,
  loading: loading.models.productmodel,
}))
@Form.create()
class ProductModel extends PureComponent {
  state = {
    modalVisible: false,
  };

  columns = [
    {
      key: 'name',
      title: formatMessage({ id: 'app.mm.productmodel.table.name' }),
      dataIndex: 'name',
    },
    {
      key: 'className',
      title: formatMessage({ id: 'app.mm.productmodel.table.category' }),
      dataIndex: 'className',
    },
    {
      key: 'desc',
      title: formatMessage({ id: 'app.mm.productmodel.table.desc' }),
      dataIndex: 'desc',
    },
    {
      key: 'createTime',
      title: formatMessage({ id: 'app.mm.productmodel.table.createTime' }),
      dataIndex: 'createTime',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.mm.productmodel.table.action' }),
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleView(record.id)}>
            <FormattedMessage id="app.mm.productmodel.table.action.view" />
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={
              <div style={{ width: 280 }}>
                <div style={{ fontWeight: 'bold', color: '000', marginBottom: 10 }}>
                  <span>
                    {formatMessage(
                      { id: 'app.mm.productmodel.del.confirm' },
                      { name: record.name },
                    )}
                  </span>
                </div>
                <div>
                  <span>{formatMessage({ id: 'app.mm.productmodel.del.prompt' })}</span>
                </div>
              </div>
            }
            onConfirm={() => this.handleDelete(record.id)}
          >
            <a>
              <FormattedMessage id="app.mm.productmodel.table.action.del" />
            </a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'productmodel/fetch',
    });
    dispatch({
      type: 'productmodel/tree',
    });
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleDelete = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'productmodel/del',
      payload: id,
    });
  };

  handleView = id => {
    router.push(`/mm/productmodel/detail/${id}`);
  };

  handleAdd = (fields, form) => {
    const { dispatch } = this.props;
    const { handleModalVisible } = this;
    dispatch({
      type: 'productmodel/add',
      payload: {
        name: fields.name,
        classId: fields.classId,
        desc: fields.desc,
      },
      form,
      handleModalVisible,
    });
  };

  render() {
    const {
      productmodel: { list, treeData, pagination, current },
      loading,
      dispatch,
    } = this.props;
    const {
      form: { getFieldDecorator, getFieldsValue },
    } = this.props;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      onShowSizeChange(curr, size) {
        dispatch({
          type: 'productmodel/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: size } },
        });
      },
      onChange(curr) {
        dispatch({
          type: 'productmodel/fetch',
          payload: {
            ...getFieldsValue(),
            ...{ pageNum: curr, pageSize: pagination.currentSize },
          },
        });
      },
    };
    const search = value => {
      dispatch({
        type: 'productmodel/fetch',
        payload: { name: value },
      });
    };
    const parentMethods = {
      modelClassData: treeData,
      current,
      handleModalVisible: this.handleModalVisible,
      handleAdd: this.handleAdd,
    };
    const { modalVisible } = this.state;
    return (
      <PageHeaderWrapper title={formatMessage({ id: 'app.mm.productmodel.title' })}>
        <div className={styles.standardList}>
          <Form layout="inline">
            <Card bordered={false}>
              <div className={styles.extraContent}>
                <Row>
                  <Col span={12}>
                    <FormItem>
                      {getFieldDecorator('name')(
                        <Search
                          className={styles.extraContentSearch}
                          placeholder={formatMessage({ id: 'app.mm.productmodel.search' })}
                          onSearch={search}
                        />,
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12} style={{ textAlign: 'right' }}>
                    <FormItem style={{ marginRight: 0 }}>
                      <Button type="primary" onClick={() => this.handleModalVisible(true)}>
                        <FormattedMessage id="app.mm.productmodel.add" />
                      </Button>
                    </FormItem>
                  </Col>
                </Row>
              </div>
              <Table
                columns={this.columns}
                dataSource={list}
                pagination={paginationProps}
                loading={loading}
                rowKey="id"
                style={{ marginTop: 15 }}
              />
            </Card>
          </Form>
        </div>
        <ProductModelForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderWrapper>
    );
  }
}
export default ProductModel;
